package com.yh.autobio.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yh.autobio.AppConfig;
import com.yh.autobio.AppContext;
import com.yh.autobio.R;
import com.yh.autobio.base.BaseFragment;
import com.yh.autobio.common.CyptoUtils;
import com.yh.autobio.common.PLog;
import com.yh.autobio.common.StringUtils;
import com.yh.autobio.common.UIHelper;
import com.yh.autobio.api.RetrofitSingleton;
import com.yh.autobio.db.WorkDatabase;
import com.yh.autobio.modules.adatper.WorkAdapter;
import com.yh.autobio.modules.bean.CM;
import com.yh.autobio.modules.bean.HeaderBean;
import com.yh.autobio.modules.bean.KCQty;
import com.yh.autobio.modules.bean.Result;
import com.yh.autobio.modules.bean.SimpleBackPage;
import com.yh.autobio.modules.bean.TeamChild;
import com.yh.autobio.modules.bean.User;
import com.yh.autobio.modules.bean.WorkBean;
import com.yh.autobio.modules.bean.WorkInfo;
import com.yh.autobio.modules.bean.WorkInfoBean;
import com.yh.autobio.modules.bean.WorkInfoGJDW;
import com.yh.autobio.modules.bean.t_my_pgdanEntry01;
import com.yh.autobio.modules.listener.HidingScrollListener;
import com.yh.autobio.modules.ui.LoginActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

import static com.yh.autobio.AppConfig.SCN_CUST_ACTION_SCODE;

public class WorkReportFragment extends BaseFragment {

    @InjectView(R.id.recyclerview)
    RecyclerView mRecyclerView;
    WorkAdapter mAdapter;
    User user;
    boolean isRun = false;//防止重复提交
    boolean isOher = false;
    int userId;
    int userGXId, userDepartmentId;
    String userName;
    String reportTime, id;
    String retoken;
    ArrayList<WorkInfo> mInfos = new ArrayList<>();
    ArrayList<t_my_pgdanEntry01> workusers = new ArrayList<>();
    //    private WorkDetailAdapter adapter;
    String checkedUsers = "";
    HeaderBean headerBean;
    WorkBean workBean;

    private BroadcastReceiver mSamDataReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(SCN_CUST_ACTION_SCODE)) {
                String message = intent.getStringExtra(AppConfig.SCN_CUST_EX_SCODE);
                handleOtherText(message);
            }
        }
    };


    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_workdetail, container, false);
        ButterKnife.inject(this, view);
        initView(view);
        initData();
        return view;
    }

    @Override
    public void initView(View view) {
        //recclerview
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.addOnScrollListener(new HidingScrollListener() {
            @Override
            public void onHide() {

            }

            @Override
            public void onShow() {

            }
        });
    }

    @Override
    public void initData() {
        user = AppContext.getInstance().getCurrentUser();
        reportTime = StringUtils.getCurTimeStr();
        headerBean = new HeaderBean();
        if (user != null) {
            headerBean.setHbcjgx(user.getDepartmentName() + "/" + user.getGXName());
            headerBean.setHbuser(user.getName());
            userGXId = user.getGXId();
            userDepartmentId = user.getFDepartmentID();
            checkedUsers = "";
            userName = user.getName();
            userId = Integer.parseInt(user.getId());
        } else {
            Snackbar.make(mRecyclerView, "获取用户失败，请重新登录", Snackbar.LENGTH_SHORT).show();
            Intent main = new Intent(mActivity, LoginActivity.class);
            startActivity(main);
            mActivity.finish();
        }
        headerBean.setReportTime(reportTime);
        String workno = getArguments().getString("workno");
        refView(workno);
        IntentFilter intentFilter = new IntentFilter(SCN_CUST_ACTION_SCODE);
        mActivity.registerReceiver(mSamDataReceiver, intentFilter);
    }

    private void refView(String workno) {
        if (!StringUtils.isEmpty(workno)) {
            //同时插入本地数据库
            new WorkDatabase(mActivity).insert(userId, userName, workno);
            headerBean.setWorkno(workno);
            fetchWorkData(workno);
        } else {
            Snackbar.make(mActivity.getWindow().getDecorView(), "请扫描工序汇报单！", Snackbar.LENGTH_SHORT).show();
            headerBean.setWorkno("请扫描派工单");
        }
    }

    @Override
    public void onDestroy() {
        mActivity.unregisterReceiver(mSamDataReceiver);
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        final int id = v.getId();
        switch (id) {
            case R.id.ll_users:
                Bundle bundle = new Bundle();
                bundle.putString("type", "select");
                UIHelper.showSimpleBackForResult(WorkReportFragment.this, mActivity, 10, SimpleBackPage.TEAM, bundle, "选择工人");
                break;
            default:
                break;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        int index_menu = 0;
        index_menu = R.menu.send_menu;
        inflater.inflate(index_menu, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.send_btn:
                if (mAdapter != null) {
                    if (mAdapter.isDYCountAll) {
                        ArrayList<t_my_pgdanEntry01> workusers = mAdapter.getWorkBean().getWorkusers();
                        Snackbar.make(mRecyclerView, "不能大于总面积", Snackbar.LENGTH_SHORT).show();
                        isRun = false;
                        return false;
                    } else {
                        if (!isRun) {
                            showWaitDialog();
                            if (mAdapter != null) {
                                WorkBean workBean1 = mAdapter.getWorkBean();
                                if (workBean1 != null) {
                                    ArrayList<WorkInfo> mcinfos = workBean1.getWorkInfos();
                                    if (mcinfos.size() == 0) {
                                        hideWaitDialog();
                                        isRun = false;
                                        Snackbar.make(mRecyclerView, "未选中任何内容", Snackbar.LENGTH_SHORT).show();
                                        return false;
                                    } else {
//                                        workusers = workBean1.getWorkusers();
//                                        if (workusers.size() < 1) {
//                                            hideWaitDialog();
//                                            isRun = false;
//                                            Snackbar.make(mRecyclerView, "至少选择一个工人", Snackbar.LENGTH_SHORT).show();
//                                            return false;
//                                        }
//                                        List<t_my_gxhbdmxEntry> t_my_gxhbdmxEntryList = new ArrayList<>();
//                                        for (int j = 0; j < workusers.size(); j++) {
//
//                                            t_my_gxhbdmxEntry gxhbdmxEntry = new t_my_gxhbdmxEntry();
//                                            gxhbdmxEntry.setFIndex(j + 1);
//                                            gxhbdmxEntry.setFgongxu(userGXId);
//                                            gxhbdmxEntry.setFAmount(workusers.get(j).getFMoney());
//                                            gxhbdmxEntry.setFHBUser(workusers.get(j).getFHBUserID());
//                                            gxhbdmxEntry.setFPrice(workusers.get(j).getFPrice());
//                                            gxhbdmxEntry.setFQty(workusers.get(j).getFAmount());
//                                            t_my_gxhbdmxEntryList.add(gxhbdmxEntry);
//                                        }
//                                        String userjsonstr = new Gson().toJson(t_my_gxhbdmxEntryList);
//                                        mcinfos.get(0).setFhbusers(userjsonstr);
                                        CM cm = new CM();
                                        cm.setToken(retoken);
                                        String jsonstr = new Gson().toJson(mcinfos);
                                        cm.setData(jsonstr);
                                        RetrofitSingleton.getApiService(mActivity).
                                                WorkUpdate(cm)
                                                .subscribeOn(Schedulers.io())
                                                .observeOn(AndroidSchedulers.mainThread())
                                                .subscribe(observer1);
                                        isRun = true;
                                    }
                                } else {
                                    Snackbar.make(mRecyclerView, "未获得数据！", Snackbar.LENGTH_SHORT).show();
                                    hideWaitDialog();
                                }
                            } else {
                                mActivity.finish();
                            }
                        } else {
                            Snackbar.make(mRecyclerView, "本次正在提交中,请勿重复提交", Snackbar.LENGTH_SHORT).show();
                            showWaitDialog("提交中...");
                        }
                    }
                    break;
                }
        }
        return true;
    }

    Observer<Result> observer1 = new Observer<Result>() {
        @Override
        public void onCompleted() {
            PLog.d("s", "onCompleted");
            hideWaitDialog();
            isRun = false;
        }

        @Override
        public void onError(Throwable e) {
            PLog.d("s", e.getMessage());
            isRun = false;
            Snackbar.make(mRecyclerView, e.getMessage(), Snackbar.LENGTH_SHORT).show();
            hideWaitDialog();
        }

        @Override
        public void onNext(Result result) {
            hideWaitDialog();
            isRun = false;
            if (result != null) {
                Object objects = result.getData();
                String message = result.getMessage();
                Gson gson = new Gson();
                if (objects != null) {
                    int code = result.getStatusCode();
                    if (code == 200) {
                        Snackbar.make(mRecyclerView, "提交汇报单成功！", Snackbar.LENGTH_SHORT).show();
//                        for (int i=0;i<mInfos.size();i++){
//                          WorkInfo info=  mInfos.get(i);
//                            if (info.getFwgtype()){
//                                mInfos.remove(i);
//                            }
//                        }
//                        tv_count_all.setText(mInfos.size()+"");
                        mInfos.clear();
//                        mAdapter = new WorkAdapter(mActivity, mInfos);
                        mRecyclerView.setAdapter(mAdapter);
//                        if (mInfos.size()==0){
//                            setHasOptionsMenu(false);
//                            Snackbar.make(tv_work_hbcjgx, "该派工单已经全部汇报了", Snackbar.LENGTH_SHORT).show();
//                        }
                    } else {
                        Snackbar.make(mRecyclerView, message, Snackbar.LENGTH_SHORT).show();
                    }
                } else {
                    Snackbar.make(mRecyclerView, message, Snackbar.LENGTH_SHORT).show();
                }
            }
        }
    };

    private void fetchWorkData(String workno) {
        String private_token = AppContext.getInstance().getProperty(AppConfig.PRIVATE_TOKEN);
        if (StringUtils.isEmpty(private_token)) {
            Snackbar.make(mRecyclerView, "登录过期，请重新登录", Snackbar.LENGTH_SHORT).show();
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);
        } else {
            retoken = CyptoUtils.decode(AppConfig.key, private_token);
            showWaitDialog("获取派工单详情...");
            RetrofitSingleton.getApiService(mActivity).
                    worksEntry(retoken, workno, "0", userGXId, userDepartmentId)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(observer);
//            RetrofitSingleton.getApiService(mActivity).
//                    GetFirstStock("asdf","asdf")
//                    .flatMap(new Func1<KCQty, Observable<Result>>() {
//                        @Override
//                        public Observable<Result> call(KCQty kcQty) {
//                            return RetrofitSingleton.getApiService(mActivity).worksEntry(retoken, "asdf", "0", userGXId, userDepartmentId);
//                        }
//                    })
//                    .subscribeOn(Schedulers.io())
//                    .observeOn(AndroidSchedulers.mainThread())
//                    .subscribe(observer);
        }
    }


    Observer<Result> observer = new Observer<Result>() {
        @Override
        public void onCompleted() {
            PLog.d("s", "onCompleted");
            hideWaitDialog();
        }

        @Override
        public void onError(Throwable e) {
            PLog.d("s", e.getMessage());
            Snackbar.make(mRecyclerView, e.getMessage(), Snackbar.LENGTH_SHORT).show();
            hideWaitDialog();
        }

        @Override
        public void onNext(Result result) {
            hideWaitDialog();
            if (result != null) {
                Object objects = result.getData();
                String message = result.getMessage();
                if (StringUtils.isEmpty(message)) {
                    message = "未获得派工单";
                }
                if (objects != null) {
                    Gson gson = new Gson();
                    String json = gson.toJson(objects);

                    WorkInfoBean myWorkbean = gson.fromJson(json, new TypeToken<WorkInfoBean>() {
                    }.getType());
                    WorkInfoGJDW workInfoGJDW = myWorkbean.getWorkGJDW();
                    List<WorkInfo> xxxxs = myWorkbean.getInfos();
                    if (xxxxs != null) {
                        if (xxxxs.size() > 0) {
                            mInfos.clear();
                            for (int i = 0; i < xxxxs.size(); i++) {
                                WorkInfo mooxinfo = xxxxs.get(i);
                                int xxxsdaiud = mooxinfo.getFgongxu();
                                if (xxxsdaiud != 0 && userGXId == xxxsdaiud) {
                                    mooxinfo.setFhbuser(userId);
                                    mInfos.add(mooxinfo);
                                } else {
                                    isOher = true;
                                }
                            }
                            if (isOher) {
                                Snackbar.make(mRecyclerView, "扫码得到的部分或全部工序数据不属于您！您无权查看", Snackbar.LENGTH_SHORT).show();
                            }
                            workBean = new WorkBean();
                            workBean.setWorkInfos(mInfos);
                            //workusers=new ArrayList<>();
                            workBean.setWorkusers(workusers);
                            if (myWorkbean != null) {
                                headerBean.setCount_all(workInfoGJDW.getFJSValue() + workInfoGJDW.getfJSName());
                                headerBean.setfJSName(workInfoGJDW.getfJSName());
                                headerBean.setOneValue(workInfoGJDW.getFJSValue() / mInfos.size());
                            }
                            workBean.setHeaderBean(headerBean);
                            workBean.setWorkusers(workusers);
                            mAdapter = new WorkAdapter(WorkReportFragment.this, mActivity, workBean);

                            mRecyclerView.setAdapter(mAdapter);

                            boolean shouldOption = false;
                            for (int k = 0; k < mInfos.size(); k++) {
                                WorkInfo mmmin = mInfos.get(k);
                                if (!mmmin.getOutFwgtype()) {
                                    shouldOption = true;
                                    k = mInfos.size();
                                }
                            }
                            setHasOptionsMenu(shouldOption);

                        } else {
                            Snackbar.make(mRecyclerView, message, Snackbar.LENGTH_SHORT).show();
                        }
                    } else {
                        Snackbar.make(mRecyclerView, message, Snackbar.LENGTH_SHORT).show();
                    }
                } else {
                    Snackbar.make(mRecyclerView, message, Snackbar.LENGTH_SHORT).show();
                }
            }
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == mActivity.RESULT_OK) {
            switch (requestCode) {
                case 10:
                    if (data != null) {
                        Bundle bundle2 = data.getExtras();
                        if (bundle2 != null) {
                            ArrayList<TeamChild> checkedChildren = (ArrayList<TeamChild>) bundle2.getSerializable("checkedChildren");
                            checkedUsers = "";
                            workusers.clear();
                            if (checkedChildren != null) {
                                String name = "{" + userName + "}" + "、";
                                for (int i = 0; i < checkedChildren.size(); i++) {
                                    t_my_pgdanEntry01 worker = new t_my_pgdanEntry01();
                                    TeamChild child = checkedChildren.get(i);
                                    if (child != null) {
                                        if (!child.getName().equals(userName)) {
                                            worker.setFHBUserName(child.getName());
                                            worker.setFHBUserID(Integer.parseInt(child.getId()));
                                            workusers.add(worker);
                                            if (i == checkedChildren.size() - 1) {
                                                checkedUsers += child.getId();
                                                name += "{" + child.getName() + "}";
                                            } else {
                                                checkedUsers += child.getId() + ",";
                                                name += "{" + child.getName() + "}" + "、";
                                            }
                                        }
                                    }
                                }
//                                tv_users_all.setText(name);
//                                final t_my_pgdanEntry01 worker1 = new t_my_pgdanEntry01();
//                                worker1.setFHBUserName(userName);
//                                worker1.setFHBUserID(userId);
//                                workusers.add(0, worker1);
                                workBean.setWorkusers(workusers);
                                mAdapter = new WorkAdapter(WorkReportFragment.this, mActivity, workBean);
                                mRecyclerView.setAdapter(mAdapter);
                                //adapter = new WorkDetailAdapter(mActivity,workusers);
//                                if (adapter!=null) {
//                                    adapter.setOnItemDeleteListener(new WorkDetailAdapter.OnItemDeleteListener() {
//                                        @Override
//                                        public void OnItemDeleteListener(int position) {
//                                            ArrayList<t_my_pgdanEntry01> workInfos = adapter.getWorkInfos();
//                                            String newName = "";
//                                            for (int i = 0; i < workInfos.size(); i++) {
//                                                if (i == workInfos.size() - 1) {
//                                                    newName += "{" + workInfos.get(i).getFHBUserName() + "}";
//                                                } else {
//                                                    newName += "{" + workInfos.get(i).getFHBUserName() + "}" + "、";
//                                                }
//                                            }
//                                            tv_users_all.setText(newName);
//                                        }
//                                    });
//                                    adapter.notifyDataSetChanged();
//                                }
                                //listview.setAdapter(adapter);
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private void handleOtherText(final String text) {
        // yhzw#gxhb#Work43
        String[] sp = text.split("#");
        if (sp != null) {
            if (sp.length >= 3) {
                if (sp[0].equals("yhzw")) {
                    if ("gxhb".equals(sp[1])) {
                        refView(sp[2]);
                    } else {
                        Snackbar.make(mRecyclerView, "错误的条码", Snackbar.LENGTH_SHORT).show();
                    }
                } else {
                    Snackbar.make(mRecyclerView, "错误的条码", Snackbar.LENGTH_SHORT).show();
                }
            } else {
                Snackbar.make(mRecyclerView, "错误的条码", Snackbar.LENGTH_SHORT).show();
            }
        } else {
            Snackbar.make(mRecyclerView, "错误的条码", Snackbar.LENGTH_SHORT).show();
        }
    }
}
